package com.frank.jpaSpecification.specification;

import com.frank.jpaSpecification.entity.Mobile;
import com.frank.jpaSpecification.entity.PageParamRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.persistence.criteria.Predicate;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 小石潭记
 * @date 2020/12/12 14:27
 * @Description: ${todo}
 */
@Component
public class MobileSpecification {

    /**
     * root 就是mobile实例  root.get("name") name是属性名 不是数据库字段名
     * @param paramRequest
     * @return
     * */
    public Specification<Mobile> getMobileSpecification(PageParamRequest paramRequest) {
        return (root, criteriaQuery, criteriaBuilder) -> {
            Predicate conjunction = criteriaBuilder.conjunction();


            List<Predicate> list = new ArrayList<>();

            String searchName = paramRequest.getSearchName();

            if (StringUtils.isNotBlank(searchName)) {
                list.add(criteriaBuilder.like(root.get("name").as(String.class), "%" + searchName + "%"));
            }

            String searchId = paramRequest.getSearchId();
            if (StringUtils.isNotBlank(searchId)) {
                list.add(criteriaBuilder.equal(root.get("id").as(Long.class), searchId));
            }

            // 模糊查询
            String searchBranch = paramRequest.getSearchBranch();
            if (StringUtils.isNotBlank(searchBranch)) {
                list.add(criteriaBuilder.like(root.get("branch").as(String.class), "%" + searchBranch + "%"));
            }

            // 前端传递价格列表，查询在列表里面的数据 in
            List<Double> priceList = paramRequest.getPriceList();
            if (!CollectionUtils.isEmpty(priceList)) {
                list.add(criteriaBuilder.and(root.get("price").as(Double.class).in(priceList)));
            }

            // 时间范围
            LocalDate startTime = paramRequest.getStartTime();
            LocalDate endTime = paramRequest.getEndTime();
            //起始日期
            if (startTime != null && !startTime.equals("")) {
                list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime").as(LocalDate.class), startTime));
            }
            //结束日期
            if (endTime != null && !endTime.equals("")) {
                list.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime").as(LocalDate.class), endTime));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };
    }

}
